# Contributor: Jakub Jirutka <jakub@jirutka.cz>
# Maintainer: Jakub Jirutka <jakub@jirutka.cz>
pkgname=lua-rapidjson
_rockname=rapidjson
pkgver=0.7.1
pkgrel=0
pkgdesc="A JSON module for Lua based on the very fast RapidJSON library"
url="https://github.com/xpol/lua-rapidjson"
arch="all"
license="MIT"
makedepends="cmake rapidjson-dev samurai"
checkdepends="lua-busted"
source="$pkgname-$pkgver.tar.gz::https://github.com/xpol/lua-rapidjson/archive/v$pkgver.tar.gz
	disable-c-cxx-flag-march.patch
	use-dromozoa-utf8.patch
	"

case "$CARCH" in
ppc64le|riscv64|loongarch64) _luajit="" ;;
*) checkdepends="$checkdepends luajit"; _luajit="jit" ;;
esac

_luaversions="5.1 5.2 5.3"
for _v in $_luaversions; do
	makedepends="$makedepends lua$_v-dev"
	checkdepends="$checkdepends lua$_v lua$_v-busted lua$_v-dromozoa-utf8"
	subpackages="$subpackages lua$_v-${pkgname#lua-}:_subpackage"
done

prepare() {
	default_prepare
	# Remove bundled rapidjson (use system package),
	# but keep bin directory - it's needed for tests.
	rm -r rapidjson/include
}

build() {
	local lver; for lver in $_luaversions; do
		mkdir -p "$builddir"/build-$lver
		cd "$builddir"/build-$lver

		msg "Building against Lua $lver..."
		cmake .. -G Ninja \
			-DCMAKE_BUILD_TYPE=MinSizeRel \
			-DCMAKE_INSTALL_PREFIX=/usr \
			-DCMAKE_CXX_FLAGS="$CXXFLAGS" \
			-DCMAKE_C_FLAGS="$CFLAGS" \
			-DCMAKE_VERBOSE_MAKEFILE=ON \
			-DBUILD_SHARED_LIBS=ON \
			-DLUA_INCLUDE_DIR="$(pkg-config --variable=includedir lua$lver)" \
			-DLUA_RAPIDJSON_VERSION="$pkgver"
		cmake --build .
	done
}

check() {
	local lver; for lver in $_luaversions $_luajit; do
		cd "$builddir"/build-${lver/jit/5.1}
		ln -sf ../rapidjson ../spec .

		msg "Testing on lua$lver"
		lua$lver /usr/bin/busted
	done
}

package() {
	mkdir -p "$pkgdir"
}

_subpackage() {
	local lver="${subpkgname:3:3}"
	pkgdesc="$pkgdesc (for Lua $lver)"
	depends="lua$lver"
	install_if="$pkgname=$pkgver-r$pkgrel lua$lver"
	local install_cmod=$(pkg-config --variable=INSTALL_CMOD lua$lver)
	local rockdir="$subpkgdir/usr/lib/luarocks/rocks-$lver/$_rockname/$pkgver-1"

	install -D -m 755 "$builddir"/build-$lver/rapidjson.so \
		"$subpkgdir"/$install_cmod/rapidjson.so

	mkdir -p "$rockdir"
	echo 'rock_manifest = {}' > "$rockdir"/rock_manifest
}

sha512sums="
e84157ddf000605cf41faf359eb51223867203cccd3c0d3597b1bc8e237ad6eda85ddf7854d97f1c57551e601f9a4389ac51143b4c51c27d21344b71e5a084dd  lua-rapidjson-0.7.1.tar.gz
90c17874ea1f5d62f5c812fbcc45bf56c734589a6ab07247dadfe76d0f8aaadb4e7e490b7ff89bc742f5b11ccf9d88a339507c321826cb91a99586f42058a757  disable-c-cxx-flag-march.patch
f42ec35dac0dec1cdd33f7275ec9576f5b2e5f7dc473a6ff434eab483632b30d884c3918d72a3ba495e2e2cfbc56488172e128eb2f9cb65c6b1c840e46ccd70a  use-dromozoa-utf8.patch
"
